package pay.portal;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pay.base.BaseCtrl;
import pay.base.ResponseBase;
import pay.common.*;
import pay.entity.SysUser;
import pay.service.IOrderJpa;
import pay.service.IUserCache;
import pay.service.sys.ISysUser;
import pay.utils.EncryptDecryptUtils;
import pay.utils.RestTemplateUtils;
import pay.utils.StringHelper;
import pay.utils.VersionUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Map;
@Controller
@EnableAutoConfiguration
@RequestMapping(value = BaseCtrl.App)
public class AllAssetsCtr {
	private Logger logger = LoggerFactory.getLogger(AllAssetsCtr.class);

	@Autowired
	private ISysUser sysUserService;
	 
	@Autowired
	private IOrderJpa OrderJPAService;

	@Autowired
	private IUserCache userCacheService;
	  
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Value("${refreshInterval}")
	private Integer  refreshInterval;//投资资产刷新时间间隔。

	@Value("${hk.host}")
	private String hkHost;
	 /**
     * 金账户baseURl，从配置文件中读取
     */
    @Value("${fy.goldAccount.baseUrl}")
    private String jzhBaseUrl;
    @Value("${fy.mchntCd}")
    private String mchnt_cd;
    @Value("${fy.goldAccount.pathBaseUrl}")
    private String pathBaseUrl;// 测试环境为/jzh 生产无。

	/**
	 * 2.8版本后资产页添加华康云数据
	 */
	private final String NEW_VERSION = "2.8";
	
    @SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/allAssets", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public void qryAllAssets(@RequestParam String userId,String accessToken,String token,String v,HttpServletResponse response) {
		
		ResponseBase<Map<String, Object>> checkErrorResp=new ResponseBase<>();
		logger.info("qryAllAssets入参userId={},accessToken={}",userId,accessToken);
		/*********************校验参数不为空*********************/
		if(StringHelper.isEmpty(userId)||StringHelper.isEmpty(accessToken)||StringHelper.isEmpty(token)){
			 checkErrorResp.setMsg(ResultCode.PARAM_LACK.getMsg());
			 checkErrorResp.setResultCode(ResultCode.PARAM_LACK.getCode());
	         writeToFront(response,checkErrorResp);
		}
		try {
			/*********************校验客户合法性*********************/
			Long LongUserId=Long.valueOf(userId);

			SysUser user = sysUserService.findById(LongUserId);
	        if (user == null || user.getCloseAccount() == 1) { // 销户的用户不给看资产-2.7.6
	        	logger.info("用户不存在！userId={}",userId);
				checkErrorResp.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
				checkErrorResp.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
	            writeToFront(response,checkErrorResp);
	        }
	        /*********************校验登陆token是否过期和是否重复登陆*********************/
	        if (!EncryptDecryptUtils.checkLogToken(token, userId)) {
				logger.info("登陆token:{}  is not exits", token);
				checkErrorResp.setMsg(ResultCode.ILLEGAL_TOKEN.getMsg());
				checkErrorResp.setResultCode(ResultCode.ILLEGAL_TOKEN.getCode());
				writeToFront(response,checkErrorResp);
			}
	        /*********************校验幂等请求*********************/
	        if (!EncryptDecryptUtils.checkToken(accessToken, userId)) {
				logger.info("查询总资产token:{}  is not exits", accessToken);
				checkErrorResp.setMsg(ResultCode.ILLEGAL_ACCESSTOKEN.getMsg());
				checkErrorResp.setResultCode(ResultCode.ILLEGAL_ACCESSTOKEN.getCode());
				writeToFront(response,checkErrorResp);
			}

			ResponseBase<AllAssetsDto> resp = new ResponseBase<AllAssetsDto>();


			//检查缓存中有没有数据，如果有则直接返回
			AllAssetsDto allAssetsDto = userCacheService.getUserAssetCache(user.getId());
			if(allAssetsDto != null) {
				resp.setMsg(ResultCode.SUCC.getMsg());
				resp.setResultCode(ResultCode.SUCC.getCode());
				resp.setResult(allAssetsDto);
				writeToFront(response, resp);
			}

	        /*********************初始化返回参数*********************/
			int virtualAccount=0;
			BigDecimal virtualLeftMoney=BigDecimal.valueOf(0.00);
			BigDecimal historyProfits=BigDecimal.valueOf(0.00);//累计收益
			BigDecimal payAmounts=BigDecimal.valueOf(0.00);
			BigDecimal allAssets=BigDecimal.valueOf(0.00);
			BigDecimal fixedAssetsCurrentDividends=BigDecimal.valueOf(0.00);
			BigDecimal fixedAssetsHistoryDividends;

			BigDecimal fixedAssetsSuccessAmts=BigDecimal.valueOf(0.00);
			int fixedAssetsCounts=0;
			BigDecimal fundConfirmAllProfit=BigDecimal.valueOf(0.00);
			BigDecimal allFundsMoney=BigDecimal.valueOf(0.00);
			int fundsAllCount=0;

			//华康宝
			BigDecimal allYingMiWallet = BigDecimal.valueOf(0.00);
			BigDecimal yingMiWalletConfirmAllProfit = BigDecimal.valueOf(0.00);

			/*********************查询客户是否在金账户开户*********************/
			String userSql="select hasVirtualAccount from SysUser where Id="+LongUserId;
			try {
				virtualAccount = jdbcTemplate.queryForObject(userSql,
						null, Integer.class);
			} catch (Exception e) {
				logger.info("查询客户是否在金账户开户异常！paymentSql={}",userSql);
				logger.error("--------------------error----------------",e);
			}

			/*********************已开通金账户则获取金账户余额*********************/
			if(virtualAccount==1){
				try {
					virtualLeftMoney=sysUserService.getUserLeftMoney(user).divide(BigDecimal.valueOf(100), 2,BigDecimal.ROUND_HALF_UP);
					allAssets=allAssets.add(virtualLeftMoney);
				} catch (Exception e) {
					logger.info("获取金账户余额异常!userId={}",userId);
					logger.error("--------------------error----------------",e);
				}
			}


			/*********************获取基金和理财类产品相关信息*********************/
			String accountId=user.getAccountId();
			String phone=user.getName();
			String url = "http://" + hkHost + "/app/allAssets/allData?userId="+userId+"&accountId="+accountId+"&phone="+phone;
			try {
				Map<String, Object> hkAssets = RestTemplateUtils.template.getForObject(url, Map.class);
				if ((hkAssets)!=null) {
					Map<String, Object> fixedAssets=(Map<String, Object>) hkAssets.get("fixedAssets");
					fixedAssetsCurrentDividends=BigDecimal.valueOf(Double.valueOf(String.valueOf(fixedAssets.get("fixedAssetsCurrentDividends")))).setScale(2, BigDecimal.ROUND_DOWN);
					fixedAssetsHistoryDividends=BigDecimal.valueOf(Double.valueOf(String.valueOf(fixedAssets.get("fixedAssetsHistoryDividends")))).setScale(2, BigDecimal.ROUND_DOWN);
					fixedAssetsSuccessAmts=BigDecimal.valueOf(Double.valueOf(String.valueOf(fixedAssets.get("fixedAssetsSuccessAmts")))).setScale(2, BigDecimal.ROUND_DOWN);

					fixedAssetsCounts=(int) fixedAssets.get("fixedAssetsCounts");
					historyProfits=historyProfits.add(fixedAssetsHistoryDividends);
					payAmounts=payAmounts.add(fixedAssetsSuccessAmts);
					allAssets=allAssets.add(fixedAssetsSuccessAmts).add(fixedAssetsCurrentDividends);

					Map<String, Object> funds=(Map<String, Object>) hkAssets.get("funds");
					fundConfirmAllProfit=BigDecimal.valueOf(Double.valueOf(String.valueOf(funds.get("fundConfirmAllProfit")))).setScale(2, BigDecimal.ROUND_DOWN);
					allFundsMoney=BigDecimal.valueOf(Double.valueOf(String.valueOf(funds.get("allFundsMoney")))).setScale(2, BigDecimal.ROUND_DOWN);
					fundsAllCount=(int) funds.get("fundsAllCount");
					historyProfits=historyProfits.add(fundConfirmAllProfit);
					allAssets=allAssets.add(allFundsMoney);

					Map<String,Object> wallets = (Map<String, Object>) hkAssets.get("wallets");
					yingMiWalletConfirmAllProfit = new BigDecimal(String.valueOf(wallets.get("yingMiWalletConfirmAllProfit")));
					allYingMiWallet = new BigDecimal(String.valueOf(wallets.get("allYingMiWallet")));
					//兼容旧版本，工资产和累计不包含华康云
					if(VersionUtil.compareVersion(v,NEW_VERSION) >= 0){
						historyProfits=historyProfits.add(yingMiWalletConfirmAllProfit);
						allAssets=allAssets.add(allYingMiWallet);
					}

				}
			} catch (Exception e) {
				logger.info("获取基金和理财类产品相关信息异常！url={}",url);
				logger.error("--------------------error----------------",e);
			}


			/*************************拼接返回值***************************/
			FixedAssetsDto fixedAssetsDto = new FixedAssetsDto();
			fixedAssetsDto.setFixedAssetsCounts(fixedAssetsCounts);
			fixedAssetsDto.setFixedAssetsCurrentDividends(fixedAssetsCurrentDividends  .setScale(2, BigDecimal.ROUND_HALF_UP));//固定资产总支出
			fixedAssetsDto.setFixedAssetsSuccessAmts( fixedAssetsSuccessAmts.setScale(2, BigDecimal.ROUND_HALF_UP));	//	固定资产



			FundsDto fundsDto = new FundsDto();
			fundsDto.setFundsAllCount(fundsAllCount);
			fundsDto.setAllFundsMoney( allFundsMoney.setScale(2, BigDecimal.ROUND_HALF_UP)); //基金总金额
			fundsDto.setFundConfirmAllProfit(fundConfirmAllProfit.setScale(2, BigDecimal.ROUND_HALF_UP));

			YingMiWalletDTO walletDTO = new YingMiWalletDTO();
			if (VersionUtil.compareVersion(v,NEW_VERSION)<0){
				walletDTO.setAllYingMiWallet(BigDecimal.valueOf(0L));
				walletDTO.setYingMiWalletConfirmAllProfit(BigDecimal.valueOf(0L));
			}else {
				walletDTO.setAllYingMiWallet(allYingMiWallet.setScale(2, BigDecimal.ROUND_HALF_UP));
				walletDTO.setYingMiWalletConfirmAllProfit(yingMiWalletConfirmAllProfit.setScale(2, BigDecimal.ROUND_HALF_UP));
			}

			allAssetsDto = new AllAssetsDto();

			allAssetsDto.setVirtualAccount(virtualAccount);
			allAssetsDto.setVirtualLeftMoney(virtualLeftMoney.setScale(2, BigDecimal.ROUND_HALF_UP));//虚拟账户余额
			allAssetsDto.setHistoryProfits(historyProfits.setScale(2, BigDecimal.ROUND_HALF_UP));
			allAssetsDto.setPayAmounts(payAmounts.setScale(2, BigDecimal.ROUND_HALF_UP));
			allAssetsDto.setAllAssets(allAssets.setScale(2, BigDecimal.ROUND_HALF_UP));//总资产
			allAssetsDto.setRefreshInterval(refreshInterval); //前端刷新时间间隔，以秒为单位


			BrokerDto  brokerDto = new BrokerDto();
			allAssetsDto.setBrokerDto(brokerDto);
			allAssetsDto.setFunds(fundsDto);
			allAssetsDto.setFixedAssets(fixedAssetsDto);
			allAssetsDto.setWalletDTO(walletDTO);

			setScale(allAssetsDto);
			resp.setMsg(ResultCode.SUCC.getMsg());
	        resp.setResultCode(ResultCode.SUCC.getCode());
	        resp.setResult(allAssetsDto);



			//将数据放入缓存
			userCacheService.setUserAssetCache(Long.valueOf(userId), allAssetsDto);

	        writeToFront(response,resp);

		} catch (Exception e) {
			logger.info("查询总资产qryAllAssets异常！userId={}",userId);
			logger.error("查询总资产qryAllAssets异常！",e);
			checkErrorResp.setMsg(ResultCode.FAILED.getMsg());
			checkErrorResp.setResultCode(ResultCode.FAILED.getCode());
	        writeToFront(response, checkErrorResp);
		}			
	}
		
    private void writeToFront(HttpServletResponse response, Object resp){
		try {
			response.setHeader("Connection", "close");
			//这句话的意思，是让浏览器用utf8来解析返回的数据  
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			//这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859 
			response.setCharacterEncoding("UTF-8");
			PrintWriter  writer=response.getWriter();
			writer.write(String.valueOf(new JSONObject(resp)));
			writer.close();
		} catch (IOException e) {
			logger.info("输出流到前端异常");
			logger.error("异常",e);
		}
	}

	private void setScale(AllAssetsDto allAssetsDto){

		BigDecimal  allAssets = allAssetsDto.getAllAssets();

		if(allAssetsDto.getAllAssets().compareTo(BigDecimal.valueOf(0)) < 1){
			allAssetsDto.setScale("0%,0%,0%,0%,0%");
		}else{
			int virtualScale= allAssetsDto.getVirtualLeftMoney().multiply(BigDecimal.valueOf(100)).divide(allAssets,0,BigDecimal.ROUND_HALF_UP).intValue();

			//总的固定资产
			BigDecimal fixedAssetsAllMoney=allAssetsDto.getFixedAssets().getFixedAssetsSuccessAmts().add(allAssetsDto.getFixedAssets().getFixedAssetsCurrentDividends());

			int fixedScale=fixedAssetsAllMoney.multiply(BigDecimal.valueOf(100)).divide(allAssets,0,BigDecimal.ROUND_HALF_UP).intValue();


			//券商类产品
			BigDecimal brokerAllMoney=allAssetsDto.getBrokerDto().getAllBrokerMoney() ;
			int brokerScale=  brokerAllMoney.multiply(BigDecimal.valueOf(100)).divide(allAssets,0,BigDecimal.ROUND_HALF_UP).intValue();

			//华康宝
			BigDecimal walletAllMoney = allAssetsDto.getWalletDTO().getAllYingMiWallet();
			int walletScale = walletAllMoney.multiply(BigDecimal.valueOf(100)).divide(allAssets,0,BigDecimal.ROUND_HALF_UP).intValue();


			int fundsScale=100-virtualScale-fixedScale - brokerScale - walletScale;
			allAssetsDto.setScale(virtualScale+"%,"+fixedScale+"%,"+fundsScale+"%," + brokerScale + "%,"+walletScale+"%");
		}
	}
}
